# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Emesene is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    emesene is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

VERSION = '0.1'

import Plugin

from urllib import urlopen
import re

#Regexes
TITLE_RE = re.compile('<h1>(.*?)</h1><br/>')
IMAGE_RE = re.compile('<img src="(http://imgs.xkcd.com/comics/.*?)" \
title="(.*?)" alt="(.*?)" /><br/>')
URL_RE   = re.compile('(?:www\.)?xkcd\.com/([0-9]*?)/')

HTML_TEMPLATE = '<div><img src="%s"/><br/><a href="%s">%s</a></div>'

def get_comic(slash_action):
    '''Get the Xkcd comic'''
    data = slash_action.getParams()
    ret = data
    if not data:
        url = 'http://xkcd.com'
    elif data == "random":
        url = 'http://dynamic.xkcd.com/comic/random/'
    else:
        ret = URL_RE.findall(data)
        if ret:
            url = 'http://xkcd.com/%s/' % ret[0]
        else:
            url = 'http://xkcd.com'

    url_fd = urlopen(url)
    data = url_fd.read()
    url_fd.close()

    title = TITLE_RE.findall(data)[0]
    img = IMAGE_RE.findall(data)[0][0]
    data = HTML_TEMPLATE % (img, url_fd.url, title)
    slash_action.conversation.ui.textview.display_html(data)

class MainClass(Plugin.Plugin):
    '''Main plugin class'''
    
    description = _('Get xkcd comic. Usage: /xkcd <random>|<url>')
    authors = {'Roger Duran' : 'rogerduran@gmail.com'}
    website = 'http://www.rogerpc.com.ar'
    displayName = 'Xkcd'
    name = 'Xkcd'
    def __init__(self, controller, msn):
        '''Contructor'''
        
        Plugin.Plugin.__init__(self, controller, msn)
        
        self.description = _('Get xkcd comic. Usage: /xkcd <random>|<url>')
        self.authors = {'Roger Duran' : 'rogerduran@gmail.com'}
        self.website = 'http://www.rogerpc.com.ar'
        self.displayName = 'Xkcd'
        self.name = 'Xkcd'
        self.slash = controller.Slash

    def start(self):
        '''start the plugin'''
        self.slash.register('xkcd', get_comic, 'Get current comic')
        self.enabled = True

    def stop(self):
        '''stop the plugin'''
        self.slash.unregister('xkcd')
        self.enabled = False

    def check( self ):
        '''Check Plugin'''
        return ( True, 'Ok' )

